import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { useUserStore } from '@/stores/user'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20*1000,
})
export interface ServiceResponse<T>{
  code:number
  msg:string
  data:T
}
export const request=<T>(url:string,method:Method='get',submitData?:object)=>{
  return service.request<T,ServiceResponse<T>>({
    url:url,
    method:method,
    //插值表达式  .toLowerCase()  将方法转换为小写
    [method.toLowerCase()==='get'?'params':'data']:submitData
  })
}
// 请求拦截器，拼接token到请求头中
service.interceptors.request.use(
  config => {
    // console.log('config',config);
    const store=useUserStore()
    if(store.token){
      config.headers.Authorization=`Bearer ${store.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)
// 响应拦截器,主要对错误进行拦截并分析错误类型
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
      if(error.response.status===401){
        router.push('/login')
        const store=useUserStore()
        store.removeStoreToken()
      }
    else{
      ElMessage.error(error.response.data.msg)
    }
  }
)

export default service
